<template>
  <div class="fx-message" :class="[type,{close:isClose,center}]" :style="messageStyle">
    <div class="content" v-if="!isHTML">{{ message }}</div>
    <div class="content" v-else v-html="message"></div>
    <span v-if="showClose" @click="closeClick"><i class="iconfont icon-multiply fs10"/></span>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, PropType, ref, SetupContext } from 'vue'
import { ComponentTypes, componentTypesArr } from '@/base/types'
import mitt, { Emitter } from 'mitt'

export interface MessageProps {
  message: string;
  type: ComponentTypes;
  center: boolean;
  offset: number;
  showClose: boolean;
  isHTML: boolean;
  isFixed: boolean;
}

export default defineComponent({
  name: 'FMessage',
  props: {
    // 消息
    message: {
      type: String as PropType<string>,
      required: true
    },
    // 类型
    type: {
      type: String as PropType<ComponentTypes>,
      default: 'success',
      validator (val: ComponentTypes): boolean {
        return componentTypesArr.includes(val)
      }
    },
    // 文字居中
    center: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    // 距离顶部距离
    offset: {
      type: Number as PropType<number>,
      default: 20
    },
    // 可关闭
    showClose: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    // 是否是html
    isHTML: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    // 是否固定位置
    isFixed: {
      type: Boolean as PropType<boolean>,
      default: false
    }
  },
  setup (props: MessageProps, ctx: SetupContext) {
    // 当前楼层数
    const currentIndex = ref<number>(0)
    // 是否关闭状态 添加关闭动画
    const isClose = ref<boolean>(false)
    // 消息监听
    const messageMitt: Emitter = mitt()

    // 关闭消息事件
    const closeMessage = (): void => {
      isClose.value = true
    }

    // 设置当前位置 根据位置计算对应的位置
    const setCurrentIndex = (val: number): void => {
      currentIndex.value = val
    }

    // 消息位置style
    const messageStyle = computed(() => {
      // 当固定位置时 直接忽略当前楼层位置
      const top = !props.isFixed ? currentIndex.value * 50 + props.offset : props.offset
      return {
        top: `${top}px`
      }
    })

    // 关闭点击事件 通知服务关闭id
    const closeClick = (): void => {
      messageMitt.emit('close', ctx.attrs.id)
    }

    return {
      isClose,
      currentIndex,
      messageStyle,
      closeClick,
      closeMessage,
      setCurrentIndex,
      messageMitt
    }
  }
})
</script>
